<template>
  <div>
    <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option
            v-for="item in list"
            :key="item.id"
            :value="item.manager"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeesSimples } from '@/api/employees'
import { addDepartments, getDepartmentDetail, updateDepartment } from '@/api/departments'

export default {
  props: {
    originList: {
      type: Array,
      required: true
    },
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data() {
    // 自定义部门编码校验规则
    const validCode = (rule, value, callback) => {
      // 获取整个部门的编码，编码的数组
      let existCodeList = this.originList.map(itme => itme.code)
      // console.log(existCodeList)
      // 如果是编辑状态，将当前编辑的部门的编码从存在的数组中移除，然后再判断
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }
      // 判断当前value值，是否在数组中存在
      if (existCodeList.includes(value)) {
        // 存在 则校验失败
        callback(new Error(`该部门编码‘${value}’已存在，请换一个编码`))
      } else {
        // 不存在 则校验通过
        callback()
      }
    }
    // 自定义校验 部门名称同级 不能重复
    const validName = (rule, value, callback) => {
      // 验证用户输入的value值（部门名称），在同级部门不能重复
      let existNameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      // console.log(existNameList)
      if (this.isEdit) {
        const pid = this.originList.find(item => item.id === this.id).pid
        const brothers = this.originList.filter(item => item.pid === pid)
        existNameList = brothers.filter(item => item.id !== this.id).map(item => item.name)
      }
      // 判断当前value值，是否在数组中存在
      if (existNameList.includes(value)) {
        // 存在 则校验失败
        callback(new Error(`该部门名称‘${value}’已存在，不能重复添加！`))
      } else {
        // 不存在 则校验通过
        callback()
      }
    }
    return {
      list: [], // 储存部门负责人列表
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }

        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.laodEmployeesSimples()
    // 只有是编辑操作才需要请求详情数据
    if (this.isEdit) {
      this.loadDepartmentDetail()
    }
  },
  methods: {
    // 获取部门详情数据
    async loadDepartmentDetail() {
      try {
        const res = await getDepartmentDetail(this.id)
        this.form = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 弹框中的数据渲染
    async laodEmployeesSimples() {
      try {
        const { data: res } = await getEmployeesSimples()
        console.log('111', res)
        res.depts.shift()
        this.list = res.depts
      } catch (error) {
        console.log(error)
      }
    },
    // 弹框新增部门！
    async  doAdd() {
      // this.form中缺少pid
      try {
        const res = await addDepartments({ pid: this.id, ...this.form })
        console.log('新增部门', res)
        // 重新渲染
        // 关闭弹层
        // 子传父
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 弹框修改部门详情信息！
    async doEdit() {
      try {
        await updateDepartment(this.form)
        // 重新渲染
        // 关闭弹窗
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 弹框确定按钮
    hSubmit() {
      this.$refs.deptForm.validate(valid => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      // this.doAdd()
      })
    },
    hCancel() {
      this.$emit('close')
    }
  }
}
</script>

<style lang="">

</style>
